<?php
/**
 * 附件 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: Attach.php 30 2012-10-15 06:08:28Z lisijie86@gmail.com $
*/

class AttachController extends BaseController {
	
	public function indexAction($params=array()) {
		$fileId = intval($params['id']);
		!$fileId && exit();
		//防盗链
		if ( ! JBlog::config('blog.remote_open') ) {
			$allow_host = explode(',', JBlog::config('blog.allow_domain'));
			$referer = parse_url($_SERVER['HTTP_REFERER']);
			if (!in_array($referer['host'], $allow_host)) {
				header('Content-Encoding: none');
				header('Content-Type: image/gif');
				header('Content-Disposition: inline; filename="open_denied.gif"');
				$fp = fopen(SYS_PATH.'Images/open_denied.gif','rb');
				fpassthru($fp);
				fclose($fp);
				exit();
			}
		}
		$attach = M('Attach', $$fileId);
		if (!$attach->exists) die('file not exists');
		
		//通过判断getimagesize取出的图片信息是否存在类型标记和色彩位深来防止伪造。
		$isimage = false;
		if (stristr($attach->filetype,'image')) {
			$imginfo = @getimagesize($attach->filepath);
			if ($imginfo[2] && $imginfo['bits']) {
				$isimage = true;
			}
			unset($imginfo);
		}
		//附件读取形式，inline直接读取，attachment下载到本地
		$disposition = $isimage ? 'inline' : 'attachment';
		//附件才统计下载次数
		if ($disposition == 'attachment') {
			$d = false;
			if ( $attachmemts = JBlog::cookie('attachmemts') ) {
				$idarr = explode(',', $attachmemts);
				if ( in_array($fileId, $idarr) ) {
					$d = true;
				}
			}
			if (!$d) {
				$attach->downloads ++;
				$attach->save();
				$attachments .= empty($attachments) ? $fileId : ','.$fileId;
				JBlog::cookie('attachmemts', $attachments);
			}	
		}
		$filetype = $attach->filetype ? $attach->filetype : 'application/octet-stream';
		$filepath = DATA_PATH.$attach->filepath;
		$originalname = basename($attach->originalname);
		if (is_readable($filepath)) {
			ob_end_clean();
			header('Cache-control: max-age=31536000');
			header('Expires: ' . JBlog::date(NOW + 31536000,'D, d M Y H:i:s') . ' GMT');
			header('Last-Modified: ' . JBlog::date($attach->dateline,'D, d M Y H:i:s') . ' GMT');
			header('Content-Encoding: none');
			header('Content-type: '.$filetype);
			header('Content-Disposition: '.$disposition.'; filename='.urlencode($originalname));
			header('Content-Length: '.$attach->filesize);
			$fp = fopen($filepath, 'rb'); 
			fpassthru($fp);
			fclose($fp);
			exit;
		} else {
			exit('file read failure!');
		}
	
	}
}
?>